// 获取收藏状态云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { itemId, itemType } = event // itemType: 'activity' | 'goods'
  
  try {
    // 直接使用openid作为用户标识
    if (!wxContext.OPENID) {
      return {
        success: false,
        message: '用户未登录',
        isCollected: false,
        isRegistered: false
      }
    }
    
    const userOpenid = wxContext.OPENID
    
    // 查找用户收藏记录
    const userCollectionResult = await db.collection('user_collection')
      .where({
        userId: userOpenid
      })
      .get()
    
    let isCollected = false
    
    if (userCollectionResult.data.length > 0) {
      const userCollection = userCollectionResult.data[0]
      const likeField = itemType === 'activity' ? 'activityLikes' : 'goodsLikes'
      const likes = userCollection[likeField] || []
      isCollected = likes.includes(itemId)
    }
    
    // 如果是活动，还需要检查报名状态
    let isRegistered = false
    if (itemType === 'activity') {
      const registrationResult = await db.collection('activity_registrations')
        .where({
          activityId: itemId,
          registrantId: userOpenid,
          status: 1 // 报名成功
        })
        .get()
      
      isRegistered = registrationResult.data.length > 0
    }
    
    return {
      success: true,
      isCollected: isCollected,
      isRegistered: isRegistered
    }
    
  } catch (error) {
    console.error('获取收藏状态失败：', error)
    return {
      success: false,
      message: '获取状态失败',
      isCollected: false,
      isRegistered: false,
      error: error.message
    }
  }
}